﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace M_Manufacture.Repository
{
    public class BaseRepository<T>:IRepository<T> where T : class
    {
        private readonly EFDbContext _context;

        public BaseRepository(EFDbContext eFDbcontext)
        {
            _context = eFDbcontext;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            await _context.AddRangeAsync(entity);

            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 添加返回ID
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsyncs(T entity)
        {
            await _context.AddAsync(entity);
            await _context.SaveChangesAsync();
            return (int)entity.GetType().GetProperty("ProcessRouteId")?.GetValue(entity);


        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await _context.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="expre"></param>
        /// <returns></returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await _context.Set<T>().Where(expre).ToListAsync();
        }


        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelsAsync(int id)
        {
            return await _context.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity)
        {
            _context.Update(entity);
            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public async Task<int> UpdateRange(List<T> entities)
        {
            _context.UpdateRange(entities);
            return await _context.SaveChangesAsync();
        }

    }
}
